package main

import (
	"fmt"
	"net/http"
)

func setCookieHandler(w http.ResponseWriter, r *http.Request) {
	//找到Cookie的对象
	cookie := &http.Cookie{
		Name:  "username",
		Value: "Hohn_doe",
	}
	//将cookie写入Cookie。
	http.SetCookie(w, cookie)
	fmt.Fprintln(w, "Cookie 设置成功!")
}

func getCookieHandler(w http.ResponseWriter, r *http.Request) {
	cookie, err := r.Cookie("username")
	if err != nil {
		fmt.Fprintln(w, "未找到Cookie")
		return
	}
	fmt.Fprintf(w, "Cookie 的值为:%s\n", cookie.Value)
}

func main() {
	http.HandleFunc("/setcookie", setCookieHandler)
	http.HandleFunc("/getcookie", getCookieHandler)

	http.ListenAndServe(":8080", nil)
}
